package com.zcyh.exam.job.quartz;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zcyh.exam.job.quartz.config.quartz.QuartzTaskScheduler;
import com.zcyh.exam.mapper.QuartzMapper;
import com.zcyh.exam.model.entity.QuartzInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 启动时处理异常调度任务
 * @author timo 2021/4/2
 */
@Component
@Slf4j
public class InitSchedulerStart implements ServletContextListener {
    @Autowired
    private QuartzMapper quartzMapper;
    @Autowired
    private QuartzTaskScheduler quartzTaskScheduler;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        List<QuartzInfo> quartzInfos = quartzMapper.selectList(Wrappers.<QuartzInfo>lambdaQuery()
                .eq(QuartzInfo::getExecStatus, "0")
                .lt(QuartzInfo::getExecDate, DateUtil.date())
        );
        quartzInfos.forEach(x->{
            Map<String, String> map = new HashMap<>();
            map.put("uuid",x.getId());
            quartzTaskScheduler.startSimpleJob(x.getServiceId(),-1,true,map);
        });
    }
}
